﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using NLBS.Security;
using NLBS.Data;
using System.Web.Security;
using NLBS.Framework;
using System.Web.UI;
using NLBS.Entity;
using NLBS.Views;
using NLBS.Data.Business;

namespace NLBS.Web.UI
{
    public class UserCommand : ICommand, IUserAction
    {
        #region Presenter

        private UserDetailPresenter _presenter;

        public UserDetailPresenter Presenter
        {
            get
            {
                if (this._presenter == null)
                    _presenter = new UserDetailPresenter();
                this._presenter.Action = this;
                return _presenter;
            }
        }

        private void PresenterInit()
        {
            this.Presenter.OnActionLoaded();
        }
        #endregion


       private Action act;
       private CallBackBase callback;
       private HttpRequest request;
       public UserCommand(Action act, CallBackBase callBack)
       {
           this.act=act;
           this.callback = callBack;
           
           
       }

        #region ICommand Members

       public void Excute()
       {
           request = this.callback.Page.Request;
           PresenterInit();
           switch (act)
           {
               case Action.Insert:
                   registerUser();
                   break;
               case Action.Select:
                   validateUser();
                   break;
               case Action.Delete:
                   deleteUser();
                   break;
               case Action.Update:
                   updateUser();
                   break;
           }
       }

        private void validateUser()
        {
            StringSecurity.CheckSecurityCode(request.Form["scode"]);
            this.Entity = new User();
            this.Entity.UserName = request.Form["user"];
            this.Entity.Password = request.Form["password"];
            LiteralControl Literal = new LiteralControl("false");
            this.ValidateUserHandler(null, null);
            
            if (this.Valid)
            {

                
                FormsAuthentication.SetAuthCookie(this.Entity.UserName, true);
                if (!string.IsNullOrEmpty(request.Form["cookiesDay"]))
                {
                    int cookiesDay = Convert.ToInt32(request.Form["cookiesDay"]);
                    if (cookiesDay > 0)
                    {
                        HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(cookiesDay);
                    }
                }
                BlogInfo.Instance().CurrentUser =this.Entity;
                Literal.Text = this.Valid.ToString();
            }
           callback.LoadControl(Literal);
        }

        private void deleteUser()
        {
            this.keyID=int.Parse(request.Form["id"]);
            this.DataDelete(null, null);
        }

        private void updateUser()
        {
            int userID = int.Parse(request.Form["userID"]);
            
            //检测用户是否存在
            this.keyID = userID;
            this.DataSelectSingle(null, null);
            User regiserUser = this.Entity;
            if (BlogInfo.Instance().CurrentUser.GroupID == 1 && regiserUser.GroupID != 1)
            {
                regiserUser.GroupID = int.Parse(request.Form["groupID"]);
            }
            regiserUser.Password = StringSecurity.StringToSHA1Hash(request.Form["password"]);
            regiserUser.Gender = int.Parse(request.Form["gender"]);
            regiserUser.Email = request.Form["email"];
            regiserUser.HideEmail = bool.Parse(request.Form["hideemail"]);
            regiserUser.Homepage = request.Form["homepage"];
            regiserUser.LastVisit = DateTime.Now;

            this.DataUpdate(null, null);
            User u = UserData.GetUserByID(userID);
            
            u.Password = regiserUser.Password;
        }

        private void registerUser()
        {
            this.Entity = new User();
            this.Entity.UserName = request.Form["username"];
            this.DataByName(null, null);
            //检测用户是否存在
            if (this.Entity != null) throw new Exception("此用户已存在,请输入其它用户名");

            StringSecurity.CheckSecurityCode(request.Form["scode"]);
            User regiserUser = new User();
            regiserUser.UserName = request.Form["username"];
            regiserUser.Password = request.Form["password"];
            regiserUser.Gender = int.Parse(request.Form["gender"]);
            regiserUser.Email = request.Form["email"];
            regiserUser.HideEmail = bool.Parse(request.Form["hideemail"]);
            regiserUser.Homepage = request.Form["homepage"];
            regiserUser.GroupID = 3;
            regiserUser.IP = RequestWrapper.IP;
            regiserUser.Salt = "";
            regiserUser.LastVisit = DateTime.Now;
            this.Entity = regiserUser;
            this.DataInsert(null, null);
        }
        #endregion

        #region IUserAction Members

        public event EventHandler ValidateUserHandler;
        private bool _valid;
        public bool Valid
        {
            get
            {
                return _valid;
            }
            set
            {
                _valid=value;
            }
        }
        private User _entity;
        public User Entity
        {
            get
            {
                return _entity;
            }
            set
            {
                _entity = value;
            }
        }

        private int _keyID;
        public int keyID
        {
            get
            {
                return _keyID;
            }
            set
            {
                _keyID = value;
            }
        }

        public event EventHandler DataInsert;

        public event EventHandler DataUpdate;

        public event EventHandler DataDelete;

        public event EventHandler DataSelectSingle;

        public event EventHandler DataByName;

        #endregion

        #region IUserAction Members


        public string repassword
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion
    }
}
